package com.hh.component;

import com.hh.controller.UserController;
import com.hh.pojo.User;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;

/**
 * 进行管理员操作时的过滤器  进行管理员操作时（比如删除分类） 必须要要求用户已登录且拥有管理员权限
 */
public class AdminInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("进入admin拦截器");
        boolean intercepted = false; // 是否被拦截
        User user = UserController.getCurrentUser(request);

        if (user == null){ //用户未登录
            request.setAttribute("status", "noLogin");
            intercepted = true;
        }else if (!("admin".equals(user.getRole()))){// 身份不是管理员
            request.setAttribute("status", "notAdmin");
            intercepted = true;
        }

        if (intercepted){ //如果被拦截下来了  进行请求转发
//            response.setContentType("text/html;charset=utf-8");   设置乱码问题  没用
            request.getRequestDispatcher("/user/handleRight").forward(request, response);
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
